import {getYMD,getNowFormatDate,getDay,formatGMTDate,sortBy,toPercent} from '../../../../assets/js/util.js' 

import echarts from 'echarts'


export default{
    data() {
        return {
            pickerOptions0: {
              disabledDate(time) {
                return time.getTime() > Date.now() - 8.64e7;
              }
            },
            // 默认参数 和 URL
            SRC: '',
            DP: {
            p: '',
            f: '',
            uid: ''
            },
            prop: '',
            order: '',      
            loading: false,
            searchable: false,
            realLoadShow: true,
            title:'副本分析',
            xlsxTitle:'',
            ftitle:'',
            ruleForm :{
                startDate:'',
                sday:'',
                eday:'',
                platForm: '0',
                channel: '0',
                tasktU: '-99999',
                tasktT: '-99999',
                server:'0'
            },
            tableHead1:[{"prop":"dateStr","label":"时间"},{"prop":"instanceType","label":"副本类型","sortable":true},{"prop":"instanceId","label":"副本id"},{"prop":"instanceName","label":"副本名称"},{"prop":"openLevel","label":"开启等级"},{"prop":"okUserNum","label":"满足条件角色数"},{"prop":"playUserNum","label":"参与角色数"},{"prop":"playRadio","label":"参与率"},{"prop":"playTimes","label":"参与次数"},{"prop":"okRadio","label":"成功率"},{"prop":"avgPlayTimes","label":"人均次数"},{"prop":"avgTime","label":"平均完成时间(m)"}],
            tableHead2a:[{"prop":"dateStr","label":"时间"},{"prop":"instanceType","label":"副本类型"},{"prop":"instanceId","label":"副本id"},{"prop":"instanceName","label":"副本名称"},{"prop":"stayUserNum","label":"停留角色数"},{"prop":"activeStayRadio","label":"活跃停留率"}],
            tableHead2b:[{"prop":"dateStr","label":"时间"},{"prop":"instanceType","label":"副本类型"},{"prop":"instanceId","label":"副本id"},{"prop":"instanceName","label":"副本名称"},{"prop":"stayUserNum","label":"停留角色数"},{"prop":"lossStayRadio","label":"流失停留率"}],
            
            
            tableHead2:[],

            mtablea1:[],
            mtableb1:[],
            mtablebAll1:[],
            mtablec1:[],
            mtabled1:[],

            mtablea2:[],
            mtableb2:[],
            mtablec2:[],
            mtabled2:[],

            mtablea3:[],
            mtableb3:[],
            mtablec3:[],
            mtabled3:[],

            mtableAll:[],

            page1:{
                pageSize: 10,
                pageSizes: [10, 20, 50, 100],
                dataTotal: 0,
                currentPage: 1,
            },
            page2:{
                pageSize: 10,
                pageSizes: [10, 20, 50, 100],
                dataTotal: 0,
                currentPage: 1,
            },
            page3:{
                pageSize: 10,
                pageSizes: [10, 20, 50, 100],
                dataTotal: 0,
                currentPage: 1,
            },
            // 全服
            servers:[],
            serNum:0,
            // 平台
            platForms:[],
            platNum:0,
            // 渠道名称
            channels:[],
            chanNum:0,
            // 任务类型
            tasktTs:[],
            tasktTNum:-99999,
            // 任务名称
            tasktUs:[],
            tasktUNum:-99999,
            activeIndex:'1',
            sheet:''
        }
    },
    computed:{
        // xlsx() {
        //     return this.title+'.xlsx'
        // }
    },
    methods: {
        // 表格下载
        excel1(tableIndex,sheet) {

            if(tableIndex ==1){
                this.xlsxTitle = sheet+"-"+this.ruleForm.sday+"到"+this.ruleForm.eday;
            }else{
                this.xlsxTitle = sheet+"-"+this.sheet+'-'+this.ruleForm.sday+"到"+this.ruleForm.eday;
            }
            if(tableIndex ==1){
                this.downloadExl(this["tableHead1"], this["mtablebAll1"],this.xlsxTitle, sheet);
            }else{
                
                this.downloadExl(this["tableHead2"], this["mtableAll"],this.xlsxTitle, sheet);
            }
        },
        // 通用 成功 与 失败
        successFun(data) {
            this.$message({
                message: data,
                type: 'success'
            });
        },
        errorFun(data) {
            this.$message.error(data);
        },
        dateChange(val){
            if(val){
                var val = val.split(" ");
                this.ruleForm.sday = val[0];
                this.ruleForm.eday = val[2];
                this.ruleForm.startDate = [this.ruleForm.sday,this.ruleForm.eday]
            }
        },
        tasktTChange(o){
        // 任务类型
        this.tasktTNum = o;
                this.apiAjax1('taskType='+o,'updateInstanceType')
        },
        tasktUChange(o){
        // 任务名称
            this.tasktUNum = o;
            this.apiAjax1('taskName='+o,'updateInstanceName')
        },
        platChange(o){
        // 平台
                this.platNum = o;
                this.apiAjax1('platform='+o,'updatePlatform')
        },
        channelChange(o){
        // 渠道
                this.chanNum = o;
                this.apiAjax1('channel='+o,'updateChannel')
        },
        serverChange(o){
        // 服务
                this.serNum = o;
                this.apiAjax1('server='+o,'updateServer')
        },
        loads() {
            this.loading = !this.loading; //加载中
            this.searchable = !this.searchable; //查询按钮不可用
        },
        handleSizeChange1(val) {
            this.mtabled1 = this.mtablea1.slice();
            this.mtabled1 = sortBy(this.mtabled1,this.prop,this.order);
            this.page1.pageSize=val;
            this.mtableb1 =this.mtablebAll1.slice((this.page1.currentPage-1)*(this.page1.pageSize),this.page1.currentPage*this.page1.pageSize);            
        },
        handleCurrentChange1(val) {
            this.mtabled1 = this.mtablea1.slice();
            this.mtabled1 = sortBy(this.mtabled1,this.prop,this.order);
            this.page1.currentPage= val;
            this.mtableb1 =this.mtablebAll1.slice((this.page1.currentPage-1)*(this.page1.pageSize),this.page1.currentPage*this.page1.pageSize);
        },        
        handleSizeChange2(val) {
            this.mtabled2 = this.mtableAll.slice();
            this.mtabled2 = sortBy(this.mtabled2,this.prop,this.order);
            this.page2.pageSize=val;
            this.page2.dataTotal = this.mtabled2.length;
            this.mtableb2 =this.mtabled2.slice((this.page2.currentPage-1)*(this.page2.pageSize),this.page2.currentPage*this.page2.pageSize);            
        },
        handleCurrentChange2(val) {
            this.mtabled2 = this.mtableAll.slice();
            this.mtabled2 = sortBy(this.mtabled2,this.prop,this.order);
            this.page2.currentPage= val;
            this.page2.dataTotal = this.mtabled2.length;
            this.mtableb2 =this.mtabled2.slice((this.page2.currentPage-1)*(this.page2.pageSize),this.page2.currentPage*this.page2.pageSize);
        },
        sortChage1({ column, prop, order }){
            this.prop = prop;
            this.order = order;

            this.mtabled1 = this.mtablea1.slice();
            this.mtabled1 = sortBy(this.mtabled1,this.prop,this.order);
            this.page1.currentPage= 1;
            this.page1.dataTotal = this.mtabled1.length;
            this.mtableb1 =this.mtabled1.slice((this.page1.currentPage-1)*(this.page1.pageSize),this.page1.currentPage*this.page1.pageSize);
        },        
        sortChage2({ column, prop, order }){
            this.prop = prop;
            this.order = order;
            this.mtabled2 = this.mtableAll.slice();
            this.mtabled2 = sortBy(this.mtabled2,this.prop,this.order);
            this.page2.currentPage= 1;
            this.page2.dataTotal = this.mtabled2.length;
            this.mtableb2 =this.mtabled2.slice((this.page2.currentPage-1)*(this.page2.pageSize),this.page2.currentPage*this.page2.pageSize);
        },
         // arrTojs
        getArrJson(arr){
            var arrNew = [];
            for(var i=0;i<arr.length;i++){
                var obj ={};
                obj.id = arr[i];
                obj.agentName = arr[i];
                arrNew.push(obj);
            }
            return arrNew;
        },
        getJsonarr(objarr){
            var arrNew = [];
            Object.keys(objarr).forEach(function(key){
                var obj = {}
                obj.id = key;
                obj.num = objarr[key];
                arrNew.push(obj)
            })
            return arrNew;
        },
        sortBy1(obj){
            return obj.sort(function(a,b){
                return parseInt(a['num']) - parseInt(b['num'])
            })
        },
    apiAjax1(keyV,aDo){
        this.$http.jsonp(`${this.SRC}data/get.do?p=${this.DP.p}&f=${this.DP.f}&a=${aDo}`,{
            params: {'ps':keyV}
        }).then(function(res){
            var data =  JSON.parse(JSON.parse(res.body));
           
                if(data.res == "0"){
                    if(aDo == 'updateServer'){
                        this.platForms =this.sortBy1(this.getJsonarr(data.platformItmes));
                        this.channels = this.sortBy1(this.getJsonarr(data.channelItmes));
                    }else if(aDo == 'updateChannel'){
                        this.platForms =this.sortBy1(this.getJsonarr(data.platformItmes));
                        this.servers = this.sortBy1(this.getJsonarr(data.serverItmes));
                    }else if(aDo == 'updatePlatform'){
                        this.channels = this.sortBy1(this.getJsonarr(data.channelItmes));						
                        this.servers = this.sortBy1(this.getJsonarr(data.serverItmes));
                    }else if(aDo == 'updateInstanceName'){
                         this.tasktTs = this.sortBy1(this.getJsonarr(data.taskType));						
                    }else if(aDo == 'updateInstanceType'){
                        this.tasktUs = this.sortBy1(this.getJsonarr(data.uiTaskNameItmes));
                    }			
            }else{
                this.errorFun(data['msg'])
            }
        }).catch(function(res){})
	},
        // 获取选择信息
        getData(){
            this.$http.jsonp(`${this.SRC}data/get.do?p=${this.DP.p}&f=${this.DP.f}&a=initParam`,{
                params: {'ps':''}
            }).then(function(res){
                var data =  JSON.parse(JSON.parse(res.body));
                if(data.res == "0"){
                    this.platForms = this.sortBy1(this.getJsonarr(data.platformItmes));
                    this.tasktUs = this.sortBy1(this.getJsonarr(data.uiInstanceNameItmes));
                    this.tasktTs = this.sortBy1(this.getJsonarr(data.instanceTypeItmes));
                    this.channels = this.sortBy1(this.getJsonarr(data.channelItmes));
                    this.servers = this.sortBy1(this.getJsonarr(data.serverItmes));  
                }else{
                    this.errorFun(data['msg'])
                }
            }).catch(function(res){
                console.log(res)
            })
        },
        search(){
            this.loads()
            this.$http.jsonp(`${this.SRC}data/get.do?p=${this.DP.p}&f=${this.DP.f}&a=search`,{
                params: {'ps':`dstart=${this.ruleForm.sday}&dend=${this.ruleForm.eday}&platform=${this.platNum}&server=${this.serNum}&instanceType=${this.tasktTNum}&channel=${this.chanNum}&instanceName=${this.tasktUNum}`}
            }).then(function(res){
                
                    var data = JSON.parse(JSON.parse(res.body).replace(/\"\{\"/g, '\{\"').replace(/\"\}\"/g, '\"\}'));
                    this.loads();
                    if(data["res"] == 0){
                        this.page1.dataTotal = data.instancePlayRadios.length;
                        this.mtablebAll1 = data.instancePlayRadios;
                        this.handleCurrentChange1(1);
                        for(var i=0;i<this.mtablea1.length;i++){
                           this.mtablea1[i].instanceId = Number(this.mtablea1[i].instanceId);
                        }

                        this.mtablea2 = data.instanceStayActiveRadios;

                        for(var i=0;i<this.mtablea2.length;i++){
                           this.mtablea2[i].instanceId = Number(this.mtablea2[i].instanceId);
                           this.mtablea2[i].activeStayRadio = toPercent(this.mtablea2[i].activeStayRadio);
                        }


                        this.mtablea3 = data.instanceStayLossRadios;

                        for(var i=0;i<this.mtablea3.length;i++){
                            this.mtablea3[i].instanceId = Number(this.mtablea3[i].instanceId);
                            this.mtablea2[i].lossStayRadio = toPercent(this.mtablea2[i].lossStayRadio);
                        }


                        this.mtablec2 = data.instanceStayActiveRadioChart;
                        this.mtablec3 = data.instanceStayLossRadiosChart;
                    
                        
                    }else{
                        this.errorFun(data['msg'])
                    }
                    this.getTableData(1)
            })
        },
        getTableData(o){
            this.activeIndex = o;
            
            this.mtableb2 = [];
            if(o==1){
                this.mtableAll = [];
                this.tableHead2 = this.tableHead2a;
                this.mtableAll = this.mtablea2;
                this.sheet = "活跃用户停留率（Top15）"
            }else if(o==2){
                this.mtableAll = [];
                this.tableHead2 = this.tableHead2b;
                this.mtableAll = this.mtablea3;
                this.sheet = "新增次日流失停留率（Top15）"
            }

            this.page2.currentPage = 1;
            this.page2.dataTotal = this.mtableAll.length;
            this.mtableb2 =this.mtableAll.slice((this.page2.currentPage-1)*(this.page2.pageSize),this.page2.currentPage*this.page2.pageSize);
            
            this.echartsData(o);
        },
         //初始化
        // 设置图表初始化宽度
        chartsWidth (el){
            if(document.getElementById(el)!==null){
                document.getElementById(el).style.width = window.innerWidth-272+"px";
            }
        },
        _init() {
            var arr = ['realTimeData'];
            for(var x=0; x<arr.length;x++){
                this.chartsWidth(arr[x]);
                this[arr[x]+'Chart'] = echarts.init(document.getElementById(arr[x]));
            }
            window.addEventListener('resize', function() {
                var resizeArr = ['realTimeDataChart']
                for(var j in resizeArr){
                    this[resizeArr[j]].resize();
                }
            }.bind(this))
        },
        // 获取表数据
        echartsData(o) {
            this.realLoadShow = false;
            if(o==1){
                var d = this.mtablec2;
            }else{
                var d = this.mtablec3;
            }

            if(d['jsonStr'] !== undefined){
                var data = d['jsonStr'];
                this.realTimeDataChart.setOption({
                    title: {
                        text: ""
                    },
                    tooltip: {
                        trigger: 'item',
                        formatter : function (params) {
                            return params.name+'<br>'+params.seriesName+'：'+toPercent(params.value)
                        }
                    },
                    legend: {
                        data:data.names
                    },
                    grid:{
                        left:'4%',
                        right:'2%',
                        bottom:'16%'
                    },
                    xAxis: [
                        {
                            type: "category",
                            splitLine: {show: false},
                            data: data.columnkeys
                        }
                    ],
                    yAxis: [
                    {
                        type: "value",
                        axisLabel: {
                            show: true,  
                            interval: 'auto',  
                            formatter: function(val){
                            val = toPercent(val);
                            return val
                            }
                        }
                    }
                    ],
                    toolbox: {
                        show : true,
                        feature : {
                            mark : {show: true},
                            dataView : {show: true, readOnly: false},
                            restore : {show: true},
                            saveAsImage : {show: true}
                        }
                    },
                    dataZoom: {
                        show: true,
                        start : 0,
                        zoomOnMouseWheel:false
                    },
                    calculable: true,
                    series: [
                        {
                            name: data.names[0],
                            type: "line",
                            showAllSymbol: true,
                            data: data.data[0],
                            itemStyle : {  
                                normal : {  
                                    lineStyle:{  
                                        color:'#2f7ed8'  
                                    },
                                    color:'#2f7ed8',  
                                }  
                            }

                        }
                    ]
                });	
            }else{

            }
        },
    },
    mounted() {
        // 初始化URL
        this.SRC = this.$store.getters.src;
        this.DP.p = localStorage.getItem('ZULONGBIPROJECTID');
        this.DP.f = localStorage.getItem('ZULONGBIPAGEID');
        this.DP.uid = localStorage.getItem('ZULONGBIUSERID');
        this.ruleForm.sday = formatGMTDate(new Date(new Date().getTime() - 1000*60*60*24*20),true,true);
        this.ruleForm.eday = formatGMTDate(new Date(new Date().getTime() - 1000*60*60*24*1),true,true);
        this.ruleForm.startDate = [this.ruleForm.sday,this.ruleForm.eday];
        this.getData();
        this.search();
        this._init();
    }
}